package com.atguigu05.communication;



class Clert {

    private int products = 0;


    public synchronized void addProducts() {

        if(products >= 20) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {

            products++;
            System.out.println(Thread.currentThread().getName() + "生产第" + products +"件商品");

            notifyAll();
        }

    }

    public synchronized void minusProduct() {

        if(products <= 0) {

            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "消费第几" + products + "件商品");
            products--;
            notifyAll();
        }
    }
}

class Producer implements Runnable {

    private Clert clert;

    public Producer(Clert clert) {
        this.clert = clert;
    }

    @Override
    public void run() {
        System.out.println("生产者开始生产商品...");
        while (true) {

            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.clert.addProducts();
        }
    }
}

class Consumer implements Runnable {

    private Clert clert;

    public Consumer(Clert clert) {
        this.clert = clert;
    }

    @Override
    public void run() {
        System.out.println("消费者开始消费产品...");
        while (true) {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            this.clert.minusProduct();
        }

    }
}

public class ProducerConsumerTest {

    public static void main(String[] args) {

        Clert clert = new Clert();
        Thread t1 = new Thread(new Producer(clert),"生产者");
        Thread t2 = new Thread(new Consumer(clert),"消费者");

        t1.start();
        t2.start();

    }
}
